package org.chmodke.proxy.client;


import org.chmodke.proxy.client.auth.GlobalAuthenticator;
import org.chmodke.proxy.client.select.GlobalProxySelector;

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 代理配置注册中心
 *
 * @author kehao
 */
public class ProxyCenter {

    private static final Map<String, Proxy> RULE = new ConcurrentHashMap<>();
    private static final Map<String, PasswordAuthentication> AUTH = new ConcurrentHashMap<>();

    private ProxyCenter() {
        ProxySelector.setDefault(GlobalProxySelector.getInstance());
        Authenticator.setDefault(GlobalAuthenticator.getInstance());
    }

    public static ProxyCenter getInstance() {
        return INNER.INSTANCE;
    }

    public Proxy getRule(String host, int port) {
        Proxy proxy = RULE.get(host + "_" + port);
        if (proxy != null) {
            return proxy;
        }
        return RULE.get(host + "_" + -1);
    }

    public PasswordAuthentication getAuth(String host, int port) {
        return AUTH.get(host + "_" + port);
    }

    public boolean register(InetSocketAddress address, Proxy proxy) {
        return register(address, proxy, null);
    }

    public boolean register(InetSocketAddress address, Proxy proxy, PasswordAuthentication auth) {
        String ruleKey = address.getHostName() + "_" + address.getPort();
        RULE.put(ruleKey, proxy);
        InetSocketAddress proxyAddr = (InetSocketAddress) proxy.address();
        String authKey = proxyAddr.getHostName() + "_" + proxyAddr.getPort();
        if (auth != null) {
            AUTH.put(authKey, auth);
        }
        return true;
    }

    private static class INNER {
        private static final ProxyCenter INSTANCE = new ProxyCenter();
    }
}


